<?php

namespace App\Admin\Actions\ShopProduct;

use App\Library\Logic\OperateLogLogic;
use App\Models\ShopProductModel;
use Encore\Admin\Actions\Response;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;

class ShopProductSaleAction extends RowAction
{
    public $name = '销量';

    public function handle(ShopProductModel $model, Request $request): Response
    {
        if (is_null($model)) return $this->response()->error(__('errorCode.433'))->refresh();
        if (empty($model->specs->toArray())) return $this->response()->error('无规格商品不可上架')->refresh();
        $model->sales = (int)$request->sales;
        $model->save();
        OperateLogLogic::add(Admin::user()->user_id, 'admin.product.editTotalSell');
        return $this->response()->success('操作成功')->refresh();
    }

    public function form(ShopProductModel $model): void
    {
        $this->text('sales', '商品销量')->default($model->product_total_sell)->rules('integer|min:1')->required()
            ->attribute('maxlength', 5)->attribute('onfocus', 'checkInteger(this)')
            ->attribute('onkeyup', 'checkInteger(this)');
    }
}
